<template>
	<div v-if="showTile" :class="['tile', currentClass, positionClass, scaleClass]">
		<div class="tile-inner">{{ number }}</div>
	</div>
</template>

<script>
	export default {
		name: "Tile",
		props: {
			/**
			 * 方块级别
			 */
			num: {
				type: Number,
				default: 2
			},
			/**
			 * 方块在游戏体中的位置
			 * x：从左往右数第x个
			 * y：从上往下数第y个
			 */
			position: {
				type: Object,
				default() {
					return {
						x: 1,
						y: 1
					}
				}
			}
		},
		data() {
			return {
				/**
				 * 当前方块级别的样式
				 */
				currentClass: 'tile-2',
				/**
				 * 方块对应位置的class
				 */
				positionClass: 'tile-position-1-1',
				scaleClass: 'anim-scale1',
				readyAnim: 'anim-scale2'
			}
		},
		methods: {
			/**
			 * 更新方块的颜色或位置
			 */
			refreshTile() {
				/*控制合理范围*/
				if (this.num > 0 && this.num <= 11) {
					this.currentClass = `tile-${this.number}`
				}
				if (this.position.x > 0 && this.position.x <= 4 && this.position.y > 0 && this.position.y <= 4) {
					this.positionClass = `tile-position-${this.position.x}-${this.position.y}`
				}
			}
		},
		computed: {
			/**
			 * 计算对应级别应该显示的数字
			 * 2的幂次方
			 */
			number() {
				if (this.num <= 1) {
					return 2
				}
				if (this.num >= 11) {
					return 2048
				}
				return Math.pow(2, this.num)
			},
			showTile() {
				return this.num !== 0
			}
		},
		watch: {
			/**
			 * 监听num和position的值改变
			 * 发生变化后刷新方块
			 */
			num() {
				this.refreshTile()
				this.scaleClass = this.readyAnim
				setTimeout(() => this.scaleClass = '', 200)
				/**
				 * 发出游戏胜利事件
				 */
				if (this.number === 2048) {
					setTimeout(() => this.$bus.$emit('gameWin'), 1000)
				}
			},
			'position': {
				handler(newValue, oldValue) {
					if (newValue.x !== oldValue.x || newValue.y !== oldValue.y) {
						this.refreshTile()
						this.$bus.$emit('positionChange')
					}
				},
				deep: true
			}
		},
		mounted() {
			this.refreshTile()
		}
	}
</script>

<style scoped>
	@import "~@/assets/css/tile.css";
	@import "~@/assets/css/tile-position.css";

	@media screen and (max-width: 520px) {
		#app .tile {
			--tile-width: 57px;
			--tile-height: 57px;
		}
		#app .tile .tile-inner {
			font-size: 35px;
		}
	}

	.tile {
		--tile-width: 107px;
		--tile-height: 107px;
		/*方块生成和数字变化动画时间*/
		--anim-time: 200ms;
		position: absolute;
		transition: all 200ms;
	}

	.tile .tile-inner {
		border-radius: 3px;
		text-align: center;
		font-weight: bold;
		z-index: 10;
		font-size: 55px;
		cursor: default;
		user-select: none;
	}

	.tile, .tile-inner {
		width: var(--tile-width);
		height: var(--tile-height);
		line-height: var(--tile-height);
	}
</style>